package org.lee.cg;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.security.SecureRandom;

/**
 * Demo
 * 使用cglib 创建代理
 *
 * @author dralee
 * @date 2022-02-11 17:44:34
 **/
public class Demo {

    public void hello() {
        System.out.println("Hello world");
    }

    public int age() {
        return new SecureRandom().nextInt(199);
    }

    public static void main(String[] args) {
        // Enhancer也不能对final类进行代理操作
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Demo.class);
        enhancer.setCallback((MethodInterceptor) (o, method, oArgs, methodProxy) -> {
            System.out.println("before method running...");
            Object result = methodProxy.invokeSuper(o, oArgs);
            System.out.println("after method running, result: " + result);
            return result;
        });

        Demo demo = (Demo) enhancer.create();
        System.out.println(demo.toString()); // 拦截了
        System.out.println(demo.getClass()); // 没有对getClass方法拦截
        System.out.println(demo.hashCode()); // 拦截了

        demo.hello(); // 拦截了
        int age = demo.age(); // 拦截了
        System.out.printf("age: %d%n", age);
    }
}
